// pages/setphone/setsmscode.js

var Define = require("../../lib/Define.js")

var _code = null
var _phone = null

/*
 * 登录
 */
var _login = function(callback){
	wx.login({success:function(res){
		callback(res.code)
	}})
}

//获取用于信息
var _getUserInfo = function(callback){

	wx.getUserInfo({
	  success: function(res){
			callback(res.userInfo)
	  },
	  fail: function() {
			callback()
	  },
	  complete: function() {
		// complete
	  }
	})
}

Page({
  data:{},
  onLoad:function(options){
    // 页面初始化 options为页面跳转所带来的参数

    _phone = options.phone

  },
  onReady:function(){
    // 页面渲染完成
  },
  onShow:function(){
    // 页面显示
  },
  onHide:function(){
    // 页面隐藏
  },
  onUnload:function(){
    // 页面关闭
  },
  onCodeInput:function(e){
    _code = e.detail.value
  },
  onDoneBtnClick:function(){
    var self = this
    if(_code){

      wx.showLoading({
        title: '加载中...',
        mask: true
      })

      wx.request({
        url: Define.value.baseUrl+"/app/user/checksmscode",
        data: {
          phone:_phone,
          code:_code,
          bid:Define.value.bid
        },
        header:{
          'content-type':'application/x-www-form-urlencoded'
        },
        method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        success: function(res){
          if(res.data.code == 200){

            _login(function(code){
              _getUserInfo(function(userInfo){
                  if(!userInfo){
                    userInfo = {}
                  }
                  userInfo.id = res.data.data.id
                  userInfo.phone = _phone
                  Define.setStoredUserInfo(userInfo)

                  wx.request({
                    url: Define.value.baseUrl+"/app/user/udpateuserinfobyid",
                    data: userInfo,
                    method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
                    header:{
                      'content-type':'application/x-www-form-urlencoded'
                    },
                    complete: function(res) {
                      wx.navigateBack({
                        delta: 1
                      })
                    }
                  })

              })
            })

          }else{
            wx.showModal({
              title: '提示',
              content: res.data.msg
            })
          }
        },
        complete:function(){
          wx.hideLoading()
        }
      })

    }else{
      wx.showModal({
        title: '提示',
        content: '请输入手机验证码',
        success: function(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  }
})